package AttachmentService

import (
	"database/sql"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/internal/service/BaseService"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
	"seawolf-admin-go/utility/tools"
	"strings"
)

func Page(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	condition := g.Map{}
	obj := db.GetUnSafaTable(ctx, req.TableName)
	countObj := db.GetUnSafaTable(ctx, req.TableName)
	// 默认全部表别名先设置为 a
	asName := "a"
	// 处理查询的列
	selectFields := ""
	defaultSelectFields := strings.Split(obj.GetFieldsStr(), ",")

	pageQueryOp := req.PageQueryOp
	if pageQueryOp != nil {
		if pageQueryOp.AsName != "" {
			asName = pageQueryOp.AsName
		}
	}
	// 有设置表别名
	obj.As(asName)
	countObj.As(asName)
	// 获取查询条件
	BaseService.GetCondition(r, condition, pageQueryOp, asName)

	obj.Where(
		condition,
	)
	countObj.Where(
		condition,
	)

	// 处理 fun_id 条件
	funId := r.Get("fun_id", 0).Int()
	if funId > 0 {
		// TODO:需要查询是否满足条件
		obj.Where("fun_id IN (?)", []int{
			0,
			funId,
		})
		countObj.Where("fun_id IN (?)", []int{
			0,
			funId,
		})
	} else {
		obj.Where("fun_id", 0)
		countObj.Where("fun_id", 0)
	}

	if pageQueryOp != nil {
		if len(pageQueryOp.SelectFields) > 0 {
			// 设置了 select 的
			selectFields = strings.Join(pageQueryOp.SelectFields, ",")
		}
		if pageQueryOp.OrderBy != "" {
			obj.Order(pageQueryOp.OrderBy)
		}
	}
	// 设置 select
	if selectFields != "" {
		obj.Fields(selectFields)
	} else {
		for k, v := range defaultSelectFields {
			defaultSelectFields[k] = asName + "." + v
		}
		obj.Fields(strings.Join(defaultSelectFields, ","))
	}
	// 处理查询里 --- end ---
	// 设置 删除时间
	obj.Where(asName + ".delete_at < 1")
	countObj.Fields("1").Where(asName + ".delete_at < 1")

	if pageQueryOp != nil {
		for _, item := range pageQueryOp.LeftJoin {
			obj.LeftJoin(item.TableInfo, item.Condition)
		}
	}
	count, countErr := countObj.Count()
	if countErr != nil {
		return response.FailByRequestMessage(nil, countErr.Error())
	}
	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	resList := res.List()
	PhotoPreFixTmp, _ := g.Cfg().Get(ctx, "upload.PhotoPreFix", "")
	PhotoPreFix := PhotoPreFixTmp.String()
	for _, item := range resList {
		item["base_url"] = PhotoPreFix
		// 处理图标
		item["icon"] = tools.GetIconByExtension(gconv.String(item["extension"]))
	}
	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"list":       resList,
			"pagination": tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}
